package cn.wubo.vrr.help.schedule;

import cn.wubo.vrr.help.entity.*;
import cn.wubo.vrr.help.service.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class EhrAllSchedule {

    @Value("${custom.ehr.start-num}")
    private String startNum;

    @Value("${custom.ehr.end-num}")
    private String endNum;

    @Autowired
    BaseInfoService baseInfoService;
    @Autowired
    EducationService educationService;
    @Autowired
    WorkService workService;
    @Autowired
    CredentialService credentialService;
    @Autowired
    ContractService contractService;
    @Autowired
    FamilyService familyService;
    @Autowired
    SalaryService salaryService;
    @Autowired
    AwardService awardService;

    private static final Integer REPEAT = 5;

    //@Scheduled(cron = "0 0 0 15 * ?")
    //@Scheduled(cron = "0/5 * * * * ?")
    @Scheduled(cron = "0 0 0 1 * ?")
    public void getEhrAllSchedule() {
        for (int i = Integer.parseInt(startNum); i <= Integer.parseInt(endNum); i++) {
            JSONObject data;
            int j = 0;
            do {
                j++;
                data = this.getEhr(i + "");
            } while (data == null && j <= REPEAT - 1);
            System.gc();
        }
    }

    public JSONObject getEhr(String emplid) {
        RestTemplate rt = new RestTemplate();
        String result = rt.postForObject("http://ehr.faw.cn/portal/talent/dashboard/notauth/all/" + emplid, null, String.class);

        System.out.println("ehr=" + emplid);
        JSONObject res = JSON.parseObject(result);
        if ("0".equals(res.getString("status")) && res.getJSONObject("data").containsKey("baseInfo")) {
            JSONObject data = res.getJSONObject("data");

            try {
                //基础信息
                BaseInfo bi = baseInfoService.saveOrUpdate((BaseInfo) this.setClassValue(BaseInfo.class, data.getJSONObject("baseInfo")));
                //学历
                educationService.saveOrUpdateAll((List<Education>) this.setClassValue(Education.class, data.getJSONArray("education")));
                //工作经历
                workService.saveOrUpdateAll((List<Work>) this.setClassValue(Work.class, data.getJSONArray("works")));
                //资格证书
                credentialService.saveOrUpdateAll((List<Credential>) this.setClassValue(Credential.class, data.getJSONArray("credentials")));
                //合同
                contractService.saveOrUpdateAll((List<Contract>) this.setClassValue(Contract.class, data.getJSONArray("contracts")));
                //家庭
                familyService.saveOrUpdateAll((List<Family>) this.setClassValue(Family.class, data.getJSONArray("families")));
                //薪酬
                List<Salary> salaries = (List<Salary>) this.setClassValue(Salary.class, data.getJSONArray("salaries"));
                salaries.forEach(e -> {
                    e.setEMPLID(bi.getEMPLID());
                });
                salaryService.saveOrUpdateAll(salaries);
                //奖励
                awardService.saveOrUpdateAll((List<Award>) this.setClassValue(Award.class, data.getJSONArray("awards")));
            } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {
                e.printStackTrace();
                System.out.println("ehr=" + emplid + " error=" + e.getMessage());
            }

            return data;
        }

        return null;
    }

    private Object setClassValue(Class<?> cla, JSONObject obj) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        Object data = cla.newInstance();
        for (String key : obj.keySet()) {
            Method setMethod = data.getClass().getMethod("set" + key, String.class);
            setMethod.invoke(data, obj.getString(key));
        }
        return data;
    }

    private List<?> setClassValue(Class<?> cla, JSONArray ja) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        List<Object> list = new ArrayList<>();
        for (Iterator iterator = ja.iterator(); iterator.hasNext(); ) {
            list.add(this.setClassValue(cla, (JSONObject) iterator.next()));
        }
        return list;
    }
}
